﻿using Cache;
using Domain.Base;
using Domain.Entity;
using DtoFw;
using DtoFw.Enum;
using Microsoft.Data.SqlClient;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Util;

namespace Repository.Base
{
    /// <summary>
    /// 基础操作类
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    public class BaseRepository<T> : IRepository<T> where T : BaseEntity, new()
    {
        /// <summary>
        /// 数据库属性
        /// </summary>
        DBAttribute attr = null;
        bool cache = false;
        string tableName = "";
        string key = "";
        private SnowFlakeGenerator worker = null;
        public BaseRepository(SnowFlakeGenerator snowFlakeGenerator)
        {
            this.worker = snowFlakeGenerator;
            Type t = typeof(T);
            tableName = t.Name;
            key = string.Format(RedisKey.EnableCacheKey, tableName);
            attr = GlobalData.Cache.Get<DBAttribute>(string.Format(RedisKey.DbKey, t.Name));
            if (attr == null)
            {
                Object[] obj = t.GetCustomAttributes(false);
                foreach (Attribute db in obj)
                {
                    if (db is DBAttribute)
                    {
                        attr = db as DBAttribute;
                        if (attr != null)
                        {
                            cache = attr.Cache;
                            GlobalData.Cache.Set(string.Format(RedisKey.DbKey, t.Name), attr);
                            break;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 获取数据库
        /// </summary>
        /// <returns></returns>
        public SqlSugarClient GetDb()
        {

            if (attr == null)
                throw new Exception("基础类未配置数据库");
            cache = attr.Cache;
            switch (attr.Database)
            {
                case EnumDatabase.Mysql:
                    return DbContext.Mysql;
                case EnumDatabase.SqlServer:
                    return DbContext.SqlServer;
            }

            return DbContext.Mysql;
        }
        /// <summary>
        /// 获取数据库
        /// </summary>
        /// <returns></returns>
        public SqlSugarClient GetDbHis()
        {

            return DbContext.Mysql;
        }
        public bool IsAny(System.Linq.Expressions.Expression<Func<T, bool>> fn)
        {
            return this.GetDb().Queryable<T>().Any(fn);
        }

        public List<T> Query(System.Linq.Expressions.Expression<Func<T, bool>> fn)
        {
            return this.GetDb().Queryable<T>().Where(fn).ToList();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req">基础查询</param>
        /// <param name="func">查询条件的方法</param>
        /// <returns></returns>
        public T Get(BaseQuery req = null, Func<ISugarQueryable<T>, ISugarQueryable<T>> funcWhere = null)
        {
            if (cache)
            {
                int code = 0;
                if (funcWhere != null)
                    code = funcWhere.Target.ToJson().GetHashCode();
                if (code > 0)
                {
                    string rk = string.Format(RedisKey.DataDetailKey, tableName, req?.Id, code);
                    var model = GlobalData.Cache.Get<T>(rk);
                    if (model != null)
                        return model;
                }
            }
            using (var db = GetDb())
            {
                var type = typeof(T);
                var linq = db.Queryable<T>().Where(x=>!x.IsDeleted);
                if (req != null)
                {
                    if (req.Id> 0)
                        linq = linq.Where(x => x.Id == req.Id);
                    if (req.Ids != null && req.Ids.Count > 0)
                        linq = linq.Where(x => req.Ids.Contains(x.Id));
                }
                if (funcWhere != null)
                    linq = funcWhere(linq);
                T entity = linq.First();
                /* if (entity != null)
                     throw new Exception($"编号{req.Id}的对象已经删除！");*/
                /*  if (tableName == "Student" || tableName == "Userinfo")
                  {
                      //脱敏解密
                      if (entity != null)
                      {
                          List<T> list = new List<T> { entity };
                          YDAESAttribute.AESDecryptProperty<T>(list);
                          entity = list[0];
                      }
                  }*/
                if (cache && entity != null)
                {
                    int code = 0;
                    if (funcWhere != null)
                        code = funcWhere.Target.ToJson().GetHashCode();
                    if (code > 0)
                    {
                        GlobalData.Cache.Set(string.Format(RedisKey.DataDetailKey, tableName, entity.Id, code), entity, (int)EnumCacheTime.Hour);
                        GlobalData.Cache.SAdd(key, string.Format(RedisKey.DataDetailKey, tableName, entity.Id));
                    }
                }
                return entity;
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req">基础查询</param>
        /// <param name="funcWhere">查询条件的方法</param>
        /// <param name="database">数据库</param>
        /// <returns></returns>
        public ISugarQueryable<T> Query(BaseQuery req = null, Func<ISugarQueryable<T>, ISugarQueryable<T>> funcWhere = null)
        {
            var type = typeof(T);

            using (var db = GetDb())
            {

                var linq = db.Queryable<T>().Where(x=> !x.IsDeleted);
                if (req == null)
                    return linq;

                if (funcWhere != null)
                    linq = funcWhere(linq);
                if (req.Id > 0)
                    return linq.Where(x => x.Id == req.Id);
                if (req.Ids != null && req.Ids.Count > 0)
                    linq = linq.Where(x => req.Ids.Contains(x.Id));

                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
                return linq;
            }
        }
        /// <summary>
        /// 查询返回受影响行数
        /// </summary>
        /// <param name="req"></param>
        /// <param name="funcWhere"></param>
        /// <returns></returns>
        public int Count(BaseQuery req = null, Func<ISugarQueryable<T>, ISugarQueryable<T>> funcWhere = null)
        {
            var type = typeof(T);
            using (var db = GetDb())
            {
                var linq = db.Queryable<T>();
                if (req == null)
                    return 0;
                if (type.BaseType.Name != "BaseNoEntity")
                    linq = linq.Where(t => !t.IsDeleted);
                if (funcWhere != null)
                    linq = funcWhere(linq);
                if (req.Id > 0)
                    return linq.Count(x => x.Id == req.Id);
                if (req.Ids != null && req.Ids.Count > 0)
                    return linq.Count(x => req.Ids.Contains(x.Id));
                return linq.Count();
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req">基础查询</param>
        /// <param name="funcWhere">查询条件的方法</param>
        /// <param name="funcSort">排序的方法，为null时，会自动以id正序进行排序；时间都一样的话，根据时间排序无效，会进行随机排序，分页则会出现bug</param>
        /// <param name="selector">返回类，不传会返回当前实体类</param>
        /// <param name="orderByType">排序枚举，不传会默认正序</param>
        /// <returns></returns>
        public Pager<T> GetPager(BaseQuery req = null, Func<ISugarQueryable<T>, ISugarQueryable<T>> funcWhere = null, Expression<Func<T, T>> selector = null, Expression<Func<T, object>> funcSort = null, OrderByType orderByType = OrderByType.Desc)
        {
            //从缓存中获取
            int code = 0;
            if (funcWhere != null)
                code = funcWhere.Target.ToJson().GetHashCode();
            if (cache)
            {
                string rk = string.Format(RedisKey.DataPageListKey, tableName, req.Page, req.PageSize, code + "");
                var model = GlobalData.Cache.Get<Pager<T>>(rk);
                if (model != null)
                    return model;
            }
            var type = typeof(T);

            using (var db = GetDb())
            {
                var linq = db.Queryable<T>();

                if (type.BaseType.Name != "BaseNoEntity")
                {
                    linq = linq.Where(t => !t.IsDeleted);
                }
                //ISugarQueryable<T> linq = dbset.Where(x => true);
                //过滤已删除项
                if (req == null)
                    return new Pager<T> { Data = linq.ToList() };
                ////排除Function表
                //if (type.Name != "Function")
                //    linq = linq.Where(x => x.AppGuid == req.AppGuid);
                //查询条件
                if (funcWhere != null)
                    linq = funcWhere(linq);
                if (req.Id > 0)
                    linq = linq.Where(x => x.Id == req.Id);
                if (req.Ids != null && req.Ids.Count > 0)
                    linq = linq.Where(x => req.Ids.Contains(x.Id));
                //if (!string.IsNullOrEmpty(req.Name))
                //    linq = linq.Where(x => x.Name.Contains(req.Name));
                //排序

                if (funcSort != null)
                    linq = linq.OrderBy(funcSort, orderByType);
                //返回响应
                var response = new Pager<T>
                {
                    TotalCount = linq.Count()
                };

                //取结果
                if (selector != null)
                    linq = linq.Select(selector);

                //分页
                if (req.Page > 0 && req.PageSize > 0)
                    linq = linq.Skip((req.Page - 1) * req.PageSize).Take(req.PageSize);

                response.Data = linq.ToList() ?? new List<T>();



                /*  if (tableName == "Student" || tableName == "Userinfo")
                  {
                      //脱敏解密
                      if (response.Data != null)
                      {
                          YDAESAttribute.AESDecryptProperty<T>(response.Data);
                      }
                  }*/
                if (cache)
                {
                    GlobalData.Cache.Set(string.Format(RedisKey.DataPageListKey, tableName, req.Page, req.PageSize, code + ""), response, (int)EnumCacheTime.Hour);
                    GlobalData.Cache.SAdd(key, string.Format(RedisKey.DataPageListKey, tableName, req.Page, req.PageSize, code + ""));
                }
                return response;
            }
        }

        /// <summary>
        /// 操作对象
        /// </summary>
        /// <param name="req">操作请求</param>
        /// <param name="action">执行方法</param>
        /// <param name="funcWhere">查询条件</param>
        /// <param name="database">数据库</param>
        /// <param name="isTransaction">是否执行事务,mysql下禁止使用事务</param>
        public void Operate(BaseOperate req, Func<ISugarQueryable<T>, ISugarQueryable<T>> funcWhere = null, Action<T, SqlSugarClient> action = null, bool isTransaction = false)
        {
            var type = typeof(T);

            using (var db = GetDb())
            {
                T obj = default(T);
                var linq = db.Queryable<T>();
                linq = linq.Where(x => !x.IsDeleted);
                //ISugarQueryable<T> linq = dbset.Where(x => true);
                //过滤已删除项
                if (req == null)
                    throw new ArgumentNullException("参数 req 为 NULL！");

                //查询条件
                //linq = linq.Where(x => x.AppGuid == req.AppGuid);
                if (req.Id.HasValue)
                    linq = linq.Where(x => x.Id == req.Id.Value);
                if (funcWhere != null)
                    linq = funcWhere(linq);
                obj = linq.First();

                if (obj == null)
                    throw new Exception($"不存在该对象！");
                if (isTransaction)
                {
                    try
                    {
                        db.Ado.BeginTran();
                        if (action != null) action.Invoke(obj, db);
                        db.Ado.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        db.Ado.RollbackTran();
                        throw new Exception($"{ex.Message}");
                    }
                }
                //删除缓存数据
                if (cache)
                {
                    List<string> members = new List<string>();
                    foreach (var member in GlobalData.Cache.SMembers(key))
                    {
                        GlobalData.Cache.Remove(member);
                        members.Add(member);
                    }
                    GlobalData.Cache.SRem(key, members.ToArray());
                }
            }
        }

        /// <summary>
        /// 操作对象
        /// </summary>
        /// <param name="req">操作请求</param>
        /// <param name="action">执行方法</param>
        /// <param name="isTransaction">是否执行事务,mysql下禁止使用事务</param>
        public void Operate(BaseOperate req, Action<T, SqlSugarClient> action, bool isTransaction = false)
        {
            Operate(req, null, action, isTransaction);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="list">对象</param>
        /// <returns></returns>
        public long Insert(T t)
        {
            if (t == null)
                throw new Exception("对象不存在！");
            var typeName = t.GetType().Name;
            if (typeName == "MinLogEntity")
                return 0;
            using (var db = GetDb())
            {
                t.Id = worker.NextId();
                t.CreateTime = DateTime.Now;
                if (db.Insertable(t).ExecuteCommandAsync().Result < 1)
                    return 0;
                return t.Id;
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="list">对象</param>
        /// <returns></returns>
        public async Task<long> InsertAsync(T t)
        {
            if (t == null)
                throw new Exception("对象不存在！");
            using (var db = GetDb())
            {
                if (t.Id < 1)
                    t.Id = worker.NextId();
                if ( await db.Insertable(t).ExecuteCommandAsync() < 1)
                    return 0;
                return t.Id;
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="action">执行保存前方法</param>
        /// <param name="isTransaction">是否执行事务,mysql下禁止使用事务</param>
        /// <returns></returns>
        public BaseEntity Save(T entity, Action<SqlSugarClient> action = null, bool isTransaction = false)
        {
            if (entity == null)
                throw new Exception("实体对象为空！");
            using (var db = GetDb())
            {
                T te = entity as T;
                if (entity == null)
                    throw new ArgumentException("实体对象不是标准实体！");
                if (entity.Id > 0)
                {
                    var type = typeof(T);
                    //原始数据
                    var oldEntity = db.Queryable<T>().Where(x => x.Id == entity.Id).First();
                    var props = type.GetProperties();
                    //排除不更新的属性
                    var ignoreProps = new List<string> { "Id", "CreateTime", "IsDeleted", "Token" };
                    foreach (var prop in props)
                    {
                        //更新属性值切不为外键属性
                        if (!ignoreProps.Contains(prop.Name) && !prop.CustomAttributes.Any(x => x.AttributeType == typeof(ForeignKeyAttribute)) && !prop.CustomAttributes.Any(x => x.AttributeType == typeof(NotMappedAttribute)))
                        {
                            var newValue = prop.GetValue(entity);
                            prop.SetValue(oldEntity, newValue);
                        }
                    }
                    entity = oldEntity as T;
                    entity.ModifyerTime = DateTime.Now;
                }
                else
                {
                    entity.Id = worker.NextId();
                    entity.CreateTime = DateTime.Now;
                    entity.IsDeleted = false;
                }
                //是否执行事务
                if (isTransaction)
                {
                    try
                    {
                        db.BeginTran();
                        action?.Invoke(db);
                        if (entity.Id == 0)
                            entity.Id = db.Insertable<T>(entity).ExecuteReturnIdentity();
                        else
                            db.Saveable<T>(entity).ExecuteCommandAsync();
                        db.CommitTran();
                        //删除缓存数据
                        if (cache)
                        {
                            List<string> members = new List<string>();
                            foreach (var member in GlobalData.Cache.SMembers(key))
                            {
                                GlobalData.Cache.Remove(member);
                                members.Add(member);
                            }
                            GlobalData.Cache.SRem(key, members.ToArray());
                        }
                    }
                    catch (Exception ex)
                    {
                        db.RollbackTran();
                        throw ex.GetBaseException();
                    }
                }
                else
                {
                    if (entity.Id == 0)
                        entity.Id = db.Insertable<T>(entity).ExecuteReturnIdentity();
                    else
                        db.Saveable<T>(entity).ExecuteCommand();
                    action?.Invoke(db);
                    //删除缓存数据
                    if (cache)
                    {
                        List<string> members = new List<string>();
                        foreach (var member in GlobalData.Cache.SMembers(key))
                        {
                            GlobalData.Cache.Remove(member);
                            members.Add(member);
                        }
                        GlobalData.Cache.SRem(key, members.ToArray());
                    }
                }
                return entity;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="req">基础条件</param>
        /// <param name="funcWhere">查询条件</param>
        /// <returns></returns>
        public int Delete(BaseOperate req, Func<ISugarQueryable<T>, ISugarQueryable<T>> funcWhere = null, Func<List<T>, List<T>> func = null)
        {
            int result = 0;
            var type = typeof(T);

            using (var db = GetDb())
            {
                var linq = db.Queryable<T>();
                linq = linq.Where(x => !x.IsDeleted);
                if (req == null)
                    throw new BizException("参数错误,req不能为null！");

                if (funcWhere == null)
                {
                    if ((!req.Id.HasValue || req.Id < 1) && (req.Ids == null || req.Ids.Count < 1))
                        throw new BizException("参数错误,删除参数异常！");
                }
                if (req.Id.HasValue && req.Id.Value > 0)
                    linq = linq.Where(x => x.Id == req.Id.Value);
                if (req.Ids != null && req.Ids.Count > 0)
                    linq = linq.Where(x => req.Ids.Contains(x.Id));
                if (funcWhere != null)
                    linq = funcWhere(linq);
                var entity = linq.ToList();
                if (entity == null)
                    throw new BizException("对象不存在！");
                entity.ForEach(x =>
                {
                    x.OperateChannel = req.OperateChannel;
                    x.ModifyerId = req.ModifyerId;
                    x.Modifyer = req.Modifyer;
                    x.IsDeleted = true;
                    x.ModifyerTime = DateTime.Now;
                });
                //修改属性
                //entity = func(entity);

                //逻辑删除
                result = db.Saveable<T>(entity).ExecuteCommand();
                //删除缓存数据
                if (cache)
                {
                    List<string> members = new List<string>();
                    foreach (var member in GlobalData.Cache.SMembers(key))
                    {
                        GlobalData.Cache.Remove(member);
                        members.Add(member);
                    }
                    GlobalData.Cache.SRem(key, members.ToArray());
                }
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="req">条件</param>
        public int Delete(BaseOperate req)
        {
            int result = 0;
            var type = typeof(T);

            using (var db = GetDb())
            {
                var linq = db.Queryable<T>();
                linq = linq.Where(x => !x.IsDeleted);
                if (req == null)
                    throw new BizException("参数错误,req不能为null！");
                if ((!req.Id.HasValue || req.Id < 1) && (req.Ids == null || req.Ids.Count < 1))
                    throw new BizException("参数错误,删除参数异常！");
                if (req.Id.HasValue && req.Id.Value > 0)
                    linq = linq.Where(x => x.Id == req.Id.Value);
                if (req.Ids != null && req.Ids.Count > 0)
                    linq = linq.Where(x => req.Ids.Contains(x.Id));
                var entity = linq.ToList();
                if (entity == null)
                    throw new Exception("对象不存在！");
                entity.ForEach(x =>
                {
                    x.OperateChannel = req.OperateChannel;
                    x.ModifyerId = req.ModifyerId;
                    x.Modifyer = req.Modifyer;
                    x.IsDeleted = true;
                    x.ModifyerTime = DateTime.Now;
                });

                //逻辑删除
                result = db.Saveable<T>(entity).ExecuteCommand();

                //删除缓存数据
                if (cache)
                {
                    List<string> members = new List<string>();
                    foreach (var member in GlobalData.Cache.SMembers(key))
                    {
                        GlobalData.Cache.Remove(member);
                        members.Add(member);
                    }
                    GlobalData.Cache.SRem(key, members.ToArray());
                }
            }
            return result;
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public int InsertBatch(List<T> list)
        {
            int result = 0;
            if (list == null)
                throw new Exception("对象不存在！");
            using (var db = GetDb())
            {
                list.ForEach(t =>
                {
                    if (t.Id < 1)
                        t.Id = worker.NextId();
                });
                //批量新增
                result = db.Insertable(list).ExecuteCommand();

                ////删除缓存数据
                //if (cache)
                //{
                //    List<string> members = new List<string>();
                //    foreach (var member in GlobalData.Cache.SMembers(key))
                //    {
                //        GlobalData.Cache.Remove(member);
                //        members.Add(member);
                //    }
                //    GlobalData.Cache.SRem(key, members.ToArray());
                //}
            }
            return result;
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public (int result, List<long> ids) InsertBatchReturn(List<T> list)
        {
            int result = 0;
            if (list == null)
                throw new Exception("对象不存在！");
            using (var db = GetDb())
            {
                list.ForEach(t =>
                {
                    if (t.Id < 1)
                        t.Id = worker.NextId();
                });
                result = db.Insertable(list).ExecuteCommand();
            }
            return (result, list.Select(x => x.Id)?.ToList());
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="request">默认ids进行查询</param>
        /// <param name="funcWhere">其他条件</param>
        /// <param name="func">修改集合</param>
        /// <returns></returns>
        public int UpdateBatch(BaseQuery request, Func<ISugarQueryable<T>, ISugarQueryable<T>> funcWhere = null, Func<List<T>, List<T>> func = null)
        {
            int result = 0;
            using (var db = GetDb())
            {
                var type = typeof(T);
                var linq = db.Queryable<T>();
                if (type.BaseType.Name != "BaseNoEntity")
                    linq = linq.Where(t => !t.IsDeleted);
                //ISugarQueryable<T> linq = dbset.Where(x => true);
                if (request != null)
                {
                    if (request.Ids != null && request.Ids.Count > 0)
                        linq = linq.Where(x => request.Ids.Contains(x.Id));
                }
                //条件查询
                if (funcWhere != null)
                    linq = funcWhere(linq);
                var list = linq.ToList();

                //修改属性
                list = func(list);
                if (list.Count > 0)
                    result = db.Saveable<T>(list).ExecuteCommandAsync().Result;

                //删除缓存数据
                if (cache)
                {
                    List<string> members = new List<string>();
                    foreach (var member in GlobalData.Cache.SMembers(key))
                    {
                        GlobalData.Cache.Remove(member);
                        members.Add(member);
                    }
                    GlobalData.Cache.SRem(key, members.ToArray());
                }
            }
            return result;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="req">条件</param>
        public int DeleteBatch(BaseOperate req)
        {
            int result = 0;
            var type = typeof(T);

            using (var db = GetDb())
            {
                var linq = db.Queryable<T>();
                if (type.BaseType.Name != "BaseNoEntity")
                    linq = linq.Where(t => !t.IsDeleted);


                //ISugarQueryable<T> linq = dbset.Where(x => true);



                if (req == null || (req.Ids == null || req.Ids.Count < 1))
                    throw new BizException("删除参数不存在！");


                linq = linq.Where(x => req.Ids.Contains(x.Id));


                var entity = linq.ToList();
                if (entity == null)
                    throw new BizException("对象不存在！");

                entity.ForEach(x =>
                {
                    x.OperateChannel = req.OperateChannel;
                    x.ModifyerId = req.ModifyerId;
                    x.Modifyer = req.Modifyer;
                    x.IsDeleted = true;
                    x.ModifyerTime = DateTime.Now;
                });

                //逻辑删除
                result = db.Saveable<T>(entity).ExecuteCommandAsync().Result;

                //删除缓存数据
                if (cache)
                {
                    List<string> members = new List<string>();
                    foreach (var member in GlobalData.Cache.SMembers(key))
                    {
                        GlobalData.Cache.Remove(member);
                        members.Add(member);
                    }
                    GlobalData.Cache.SRem(key, members.ToArray());
                }
            }
            return result;
        }
        /// <summary>
        /// 生成类
        /// </summary>
        /// <param name="tables">表集合</param>
        /// <param name="dir"></param>
        /// <param name="space"></param>
        private void BuildClssToDB(string[] tables,
            string dir, string space)
        {
            using (var db = GetDb())
            {

                if (tables == null || tables.Length > 0)
                    db.DbFirst.Where(tables)
                        .CreateClassFile(dir, space);
                else
                    db.DbFirst.CreateClassFile(dir, space);
            }
        }
        /// <summary>
        /// 获取种子
        /// </summary>
        /// <param name="seedName"></param>
        /// <returns></returns>
        private static readonly object seedLock = new object();
        public int GetSeed(string seedName)
        {
            string sql = @"SELECT NEXT VALUE FOR " + seedName + "";
            using (var db = GetDb())
            {
                lock (seedLock)
                {
                    int seed = db.Ado.GetInt(sql, new { });
                    return seed;
                }
            }
        }
        /// <summary>
        /// 批量执行sql
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool ExecSqlTran(List<string> list)
        {
            bool result = false;
            string text = string.Empty;
            string empty = string.Empty;
            using (SqlConnection dbConnection =
                    new SqlConnection(GlobalData.DbConnect.SqlServer))
            {
                dbConnection.Open();
                using (SqlTransaction dbTransaction = dbConnection.BeginTransaction())
                {
                    try
                    {
                        for (int j = 0; j < list.Count; j++)
                        {
                            string text2 = list[j];
                            text = text + text2 + ";" + Environment.NewLine;
                            if (text2.Trim().Length > 1)
                            {
                                SqlCommand sqlCommand = new SqlCommand(text2,
                                    dbConnection, dbTransaction);
                                result = sqlCommand.ExecuteNonQuery() < 0;
                                if (result)
                                    break;
                            }
                        }
                        if (!result)
                            dbTransaction.Commit();
                    }
                    catch (Exception ex2)
                    {
                        dbTransaction.Rollback();
                        throw;
                    }
                }
                return !result;
            }
        }
    }
}
